package rpc;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import config.RabbitConfig;

import java.io.IOException;

/**
 * @author tuyou_cd
 * @date 2020/12/18 14:46
 */
public class RPCServer {
    public static final String RPC_QUEUE_NAME = "request_queue";

    public static void main(String args[]) throws Exception {
        Channel channel = RabbitConfig.createChannel();

        channel.queueDeclare(RPC_QUEUE_NAME, false, false, false, null);
        channel.basicQos(1);

        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                AMQP.BasicProperties replyProps = new AMQP.BasicProperties.Builder()
                        .correlationId(properties.getCorrelationId())
                        .build();
                String message = new String(body);
                int n = Integer.parseInt(message);
                String response = String.valueOf(n * n);
                System.out.println(" [.] n*n(" + message + ")=" + response);
                channel.basicPublish("", properties.getReplyTo(), replyProps, response.getBytes());
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        };
        channel.basicConsume(RPC_QUEUE_NAME, false, consumer);
        System.out.println(" [x] Awaiting RPC requests");
    }
}
